package report.service.tree.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import report.dao.po.ReportTreeDO;
import report.dao.repository.ReportTreeRepository;
import report.dao.vo.tree.TreeVO;
import report.service.tree.ITreeService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TreeServiceImpl implements ITreeService {

    @Autowired
    private ReportTreeRepository reportTreeRepository;

    @Override
    public TreeVO getTree(String id) {
        return null;
    }

    @Override
    // 获取所有目录
    public List<TreeVO> getTree() {
        // 从根节点开始
        List<ReportTreeDO> dos = reportTreeRepository.findAll();
        List<TreeVO> ret = fn(dos,"0");
        return  ret;

    }

    // 一个递归函数
    private List<TreeVO> fn(List<ReportTreeDO> data, String pid){

        return data.stream().filter(d->d.getTypeCode().equals("0") && d.getPid().equals(pid)).map(it->{
            TreeVO treeVO = TreeVO.do2vo(it);
            List<TreeVO> children = fn(data,treeVO.getId());
            if(children.size()>0){
                treeVO.setChildren(children);
            }
            return treeVO;
        }).collect(Collectors.toList());


    }

    /**
     * 创建目录
     * @param pid
     * @param name
     * @return
     */
    public String createCata(String pid, String name,String typeCode){
        ReportTreeDO treeVO  = new ReportTreeDO();
        treeVO.setPid(pid);
        treeVO.setName(name);
        treeVO.setTypeCode(typeCode);

        reportTreeRepository.save(treeVO);

        return "success";
    }

    /**
     * 更新目录
     * @param id
     * @param pid
     * @param name
     * @return
     */
    public String updateCata(String id, String pid, String name){
        ReportTreeDO treeVO  = new ReportTreeDO();
        treeVO.setPid(pid);
        treeVO.setName(name);
        treeVO.setId(id);
        treeVO.setTypeCode("0");

        reportTreeRepository.saveAndFlush(treeVO);

        return "success";
    }

    /**
     * 删除目录，以及下面所有目录和报表
     * @param id
     * @return
     */
    public String deleteCata(String id){
        // 删除自己
       reportTreeRepository.delete(id);
       // 删除子节点
        List<ReportTreeDO> dos = reportTreeRepository.findAllByPid(id);
        reportTreeRepository.deleteInBatch(dos);

        return "success";
    }
}
